<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { createGoodsApi, deleteGoodsApi, updateGoodsApi, getGoodsApi, uploadGoodsImageApi } from "@/api/goods"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"
import { CATEGORY } from "@/constants"

defineOptions({
  // 命名当前组件
  name: "Order"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA = {
  id: undefined,
  productName: "",
  brand: "",
  categoryId: undefined,
  categoryName: "",
  description: "",
  price: 0,
  rating: 0,
  status: 0,
  imageUrl: "",
  stockQuantity: 0
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref(cloneDeep(DEFAULT_FORM_DATA))
const formRules = {}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = formData.value.id === undefined ? createGoodsApi : updateGoodsApi
    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
  imageUrl.value = ""
}
//#endregion

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`正在删除，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteGoodsApi({ ids: [row.id] }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: any) => {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
  imageUrl.value = row.fileAllPath
}
//#endregion

//#region 查

const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  productName: "",
  description: "",
  categoryId: ""
})
const tableData = ref<any[]>([])
const getTableData = () => {
  loading.value = true
  getGoodsApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    ...searchData
  })
    .then(({ data }: any) => {
      paginationData.total = data.total
      tableData.value = data.records
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// 查看评价
const commentVisible = ref<boolean>(false)
const commentData = ref<any[]>([])
// const viewComment = (productReviews: any) => {
//   commentVisible.value = true
//   if (productReviews) {
//     commentData.value = productReviews
//   }
// }

// #region 导入
const fileList = ref([])
const imageUrl = ref("")
function handleExceed(files: any, fileList: any) {
  ElMessageBox.alert(
    `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
    "提示",
    {
      confirmButtonText: "确定",
      type: "warning"
    }
  )
}
function handleSuccess(res: any) {
  formData.value.imageUrl = res.result.filePath
  imageUrl.value = res.result.fileUrl
  fileList.value = []
}
function handleError(err: any) {
  console.error(err)
  ElMessageBox.alert("导入失败！", "提示", {
    confirmButtonText: "确定",
    type: "error"
  })
}

const headers = {
  Authorization:
    "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNp8U79v1DAU_l88H9ROHNvpBunQDFRIZQFFQk7i3kUldpTYQ6k6ILiqSB1aCSEGFgZEpyIxUOlU8dcQrkz9F3CSS-5ORfUQ-b3v_fi-95xDYCpRhnJPgU1wGAGeJMpIvWPyWJQR2IxAECD_0daTcCcCI4uPhfVCe0tKwbUIU2uiwXyW5Q2OiA8pdR2MIGxiszaKuIQQjCGhGCLmI4Zb6OlEafWYJ_ttu408k5nqvg9ik-wLvSES5MYoZQzH2HF4SniCKCYexHscYg-_tP0QdQhkDPnuw0KOW66ZXNJxEPIcCBd0pDJ6V3NtqgX7Fc-u7nTXVz_q6df68-z2-uTmzent9fuuaBWovHgldD-HpWPI_DWtL0_rj-8WCVtiLTxMu-kGE9FqbrzSdi7FmjFUO57-fXvxezarzz-1BVU55jJ7zXWmZKBS0UZZYXfAbjeEecxDDmUOoZ6LHNJMvZgoKVaW3OZWypRJT6Lqx7M0BkZn3-cfLtoULSSXOlxbr-shTImPIWsCDoq-opGZvsO3cd7D0xTp6iPrzH6rFCLiUc8n3VabhzzUf7H9fBv2B3WtLC553uE3P6fz2bf55Zf52bEdrNXz5-QqAkdgBLQtbwXnRdPCdnARRD5x6WhQa3-V_6i1qZWJLVblFTj6BwAA__8.is1nEhWRqtUHxs-VrUuzx7gw7KCffx7MPhJH1exg2AI"
}

// #endregion
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="searchData.productName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="searchData.description" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-form-item label="分类名称" prop="categoryId" w-200px>
            <el-select v-model="searchData.categoryId" placeholder="请选择分类">
              <el-option v-for="item in CATEGORY" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增</el-button>
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column prop="productName" label="商品名称" align="center" />
          <!-- <el-table-column prop="brand" label="品牌" align="center" /> -->
          <el-table-column prop="categoryName" label="分类名称" align="center" />
          <!-- <el-table-column prop="description" label="商品描述" align="center" /> -->
          <el-table-column prop="price" label="价格" align="center" />
          <el-table-column prop="rating" label="评分" align="center" />
          <el-table-column prop="stockQuantity" label="库存" align="center" />
          <el-table-column prop="createdTime" label="创建时间" align="center" />
          <el-table-column prop="fileAllPath" label="图片" align="center">
            <template #default="scope">
              <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.fileAllPath"
                fit="cover"
                :preview-teleported="true"
                :preview-src-list="[scope.row.fileAllPath]"
              />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.status === 0">上架</el-tag>
              <el-tag type="danger" v-else>下架</el-tag>
            </template>
          </el-table-column>
          <!-- 查看评价 -->
          <!-- <el-table-column prop="status" label="评价列表" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="viewComment(scope.row.productReviews)"
                >查看</el-button
              >
            </template>
          </el-table-column> -->

          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === undefined ? '新增' : '修改'"
      @closed="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="formData.productName" />
        </el-form-item>
        <!-- <el-form-item label="品牌" prop="brand">
          <el-input v-model="formData.brand" />
        </el-form-item> -->
        <el-form-item label="分类名称" prop="categoryName">
          <el-select v-model="formData.categoryId" placeholder="请选择分类">
            <el-option v-for="item in CATEGORY" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="商品描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item> -->
        <el-form-item label="价格" prop="price">
          <el-input v-model="formData.price" />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-input v-model="formData.rating" />
        </el-form-item>
        <el-form-item label="库存" prop="stockQuantity">
          <el-input v-model="formData.stockQuantity" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="0">上架</el-radio>
            <el-radio :value="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="fileAllPath">
          <el-upload
            :action="uploadGoodsImageApi"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
            :show-file-list="false"
            mr="12px"
            :headers="headers"
            :data="{
              storeIndex: 0,
              filePurpose: '用途',
              fileDesc: '描述'
            }"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100px; height: 100px" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>

    <!-- 评价列表 -->
    <el-dialog v-model="commentVisible" title="评价列表" width="50%">
      <el-table :data="commentData">
        <el-table-column prop="reviewerName" label="用户名" align="center" />
        <el-table-column prop="reviewText" label="评价内容" align="center" />
        <el-table-column prop="reviewDate" label="评价时间" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
</style>
